<template>
  <div class="container">
    <!-- 头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>栏目</el-breadcrumb-item>
      <el-breadcrumb-item>添加栏目</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="90px"
        label-position="left"
      >
        <el-form-item label="序号" class="sort">
          <el-input type="number" v-model="addCateForm.sort"></el-input>
        </el-form-item>
        <el-form-item label="上级栏目">
          <el-select v-model="addCateForm.pid">
            <el-option label="请选择" :value="0">--</el-option>
            <el-option v-for="item in cateList" :key="item.id" :label="item.name" :value="item.id">
              {{ item.name }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name" class="name">
          <el-input v-model="addCateForm.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addCate">添加栏目</el-button>
          <el-button @click="$router.push('/home/cate')">返回列表</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'CateAdd',
  data() {
    return {
      // 添加栏目表单数据对象
      addCateForm: {
        sort: 0,
        pid: 0,
        name: ''
      },
      // 添加栏目表单规则对象
      addCateFormRules: {
        name: [{ required: true, message: '请输入栏目名称', trigger: 'blur' }]
      },
      // 分类列表
      cateList: []
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取一级分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('/home/cate')
      this.cateList = res
    },
    // 添加栏目
    addCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        // 发起添加栏目的网络请求
        const { data: res } = await this.$http.post('/admin/cate', this.addCateForm)
        // 添加失败
        if (res.status !== 200) return this.$message.error(res.msg)
        // 添加成功
        this.$message.success(res.msg)
        // 返回列表
        this.$router.push('/home/cate')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.sort {
  width: 210px;
}

.name {
  width: 310px;
}
</style>
